package org.shana.shortlink.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.shana.shortlink.admin.common.convention.exception.ClientException;
import org.shana.shortlink.admin.common.convention.result.Results;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static org.shana.shortlink.admin.common.enums.UserErrorCodeEnum.USER_TOKEN_FAIL;

/**
 * 用户信息传输过滤器
 */
@RequiredArgsConstructor
@Slf4j
public class UserTransmitFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;
    private static final List<String> IGNORE_URI = Lists.newArrayList(
            "/api/v1/short-link/admin/user/login",
            "/api/v1/short-link/admin/user/has-username",
            "/api/v1/short-link/admin/user/register"
    );

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        log.info("请求的路径是：{}",requestURI);
        if(!myDoFilter(requestURI)) {
            if (!IGNORE_URI.contains(requestURI)) {
                String method = httpServletRequest.getMethod();
                if (!(Objects.equals(requestURI, "/api/v1/short-link/admin/user") && Objects.equals(method, "POST"))) {
                    String username = httpServletRequest.getHeader("username");
                    String token = httpServletRequest.getHeader("token");
                    log.info("username:{},token:{}", username, token);
                    if (!StrUtil.isAllNotBlank(username, token)) {
                        returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                        ((HttpServletResponse) servletResponse).setStatus(HttpStatus.UNAUTHORIZED.value());
                        return;
                    }
                    Object userInfoJsonStr;
                    try {
                        userInfoJsonStr = stringRedisTemplate.opsForHash().get("login:" + username, token);
                        if (userInfoJsonStr == null) {
                            ((HttpServletResponse) servletResponse).setStatus(HttpStatus.UNAUTHORIZED.value());
                            throw new ClientException(USER_TOKEN_FAIL);
                        }
                    } catch (Exception ex) {
                        returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                        ((HttpServletResponse) servletResponse).setStatus(HttpStatus.UNAUTHORIZED.value());
                        return;
                    }
                    //延时
                    stringRedisTemplate.expire("login:" + username, 60L, TimeUnit.MINUTES);
                    UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
                    UserContext.setUser(userInfoDTO);
                }
            }
        }
        try {
            log.debug("忽略并放行请求");
            log.info("忽略并放行请求-----------------");
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }


    boolean myDoFilter(String url){
        /*
        url: /dawede
        url: /api/v1/...
         */
        int index = url.substring(1).indexOf('/');
        return index==-1;
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
//        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//        String requestURI = httpServletRequest.getRequestURI();
//        log.info("请求的路径是：{}",requestURI);
//        if (!Objects.equals(requestURI, "/api/short-link/admin/v1/user/login")) {
//            String username = httpServletRequest.getHeader("username");
//            String token = httpServletRequest.getHeader("token");
//            log.info("username:{},token:{}",username,token);
//            Object userInfoJsonStr;
//            try {
//                userInfoJsonStr= stringRedisTemplate.opsForHash().get("login:" + username, token);
////                userInfoJsonStr= stringRedisTemplate.opsForHash().get("login:" + null, token);神奇，他又不报错illegalArgumentException了
//            }catch (IllegalArgumentException e){
//                throw new ServletException("用户未登录，redis查不到键报错");
//            }
//            if (userInfoJsonStr != null) {
//                UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
//                UserContext.setUser(userInfoDTO);
//            }
//            else {
//                //尽管redis找不到这个键会报错，但是为了代码的健壮性，还是写一下
//                throw new ClientException("用户不存在或未登录");
////                return;
//            }
//        }
//        try {
//            filterChain.doFilter(servletRequest, servletResponse);
//        } finally {
//            UserContext.removeUser();
//        }
//    }
}